/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean;

import java.io.IOException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.export.*;
import java.util.*;
import javax.persistence.EntityManager;
import entity.PaymentManagementEntity;
import entity.StakeholderEntity;
import javax.ejb.EJB;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import net.sf.jasperreports.engine.util.JRLoader;
import org.primefaces.event.SelectEvent;
import session.stateful.ReportSessionBean;
import session.stateful.StakeholderSessionBeanStateful;
import session.stateful.TransactionSessionBean;

/**
 *
 * @author Dao Thai Duy
 */
@ManagedBean(name = "reportManagerBean")
@RequestScoped
public class ReportManagerBean {

    private EntityManager entityManager;
    @EJB
    private TransactionSessionBean transactionSessionBean;
    @EJB
    private StakeholderSessionBeanStateful stakeholderSessionBean;
    @EJB
    private ReportSessionBean reportSessionBean;
    private StakeholderEntity selectedStakeholder;
    private PaymentManagementEntity selectedBill;
    private FacesContext ctx = FacesContext.getCurrentInstance();

    /** Creates a new instance of ReportManagerBean */
    public ReportManagerBean() {
    }

    public void initGenerateReport(PhaseEvent event) {
        setSelectedStakeholder((StakeholderEntity) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("stakeholder"));
//        selectedBill=getTransactionSessionBean().getCurrentBill(getSelectedStakeholder());
        System.out.println(getSelectedStakeholder() != null);
    }

    public void redirect(ActionEvent event) throws IOException {
        String serverName = ctx.getExternalContext().getRequestServerName();
        int serverPort = (Integer) ctx.getExternalContext().getSessionMap().get("serverPort");
        String contextPath = ctx.getExternalContext().getRequestContextPath();
        ctx.getExternalContext().redirect("http://" + serverName + ":" + serverPort + contextPath + "/report/reportBill" + selectedStakeholder.getId() + selectedBill.getId() + ".pdf");
    }

    public void testCreateBill() throws ClassNotFoundException {
        PaymentManagementEntity currentBill = null;
        currentBill = getTransactionSessionBean().getCurrentBill(getSelectedStakeholder());
        System.out.println("currentBill " + currentBill.getId());
        createBill(currentBill);
//        reportSessionBean.doCreateBill();
    }

    public void createBill(PaymentManagementEntity currentBill) throws ClassNotFoundException {
        HashMap parameterMap = new HashMap();
        JasperReport jasperReport;
        Connection connection = establishConnection();

        try {
            jasperReport = JasperCompileManager.compileReport("C://IS3102Project//report//reportBill.jrxml");
//            jasperReport= (JasperReport)JRLoader.loadObject(("reportBill.jasper"));
//            parameterMap.put("previousBilling", previousBill.getTotalPaymentCurrent());
//            parameterMap.put("previousPaymentLeft", previousBill.getPaymentLeft());
//            parameterMap.put("previousPaymentReceived", previousBill.getPaymentReceived());
            parameterMap.put("currentBillingId", currentBill.getId());
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameterMap, connection);

            JasperExportManager.exportReportToPdfFile(jasperPrint, "C://IS3102Project//IS3102Project-war//web//report//reportBill" + selectedStakeholder.getId() + currentBill.getId() + ".pdf");
//            JasperExportManager.exportReportToHtmlFile(jasperPrint, "D://NetBeansProjects//IS3102Project//IS3102Project-war//web//reportBill.html" );

//            JRXlsExporter exporter = new JRXlsExporter();
//            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            //export report to Excel
//            exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "D://simple_report.xls" );
//            exporter.exportReport();
        } catch (JRException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static Connection establishConnection() throws ClassNotFoundException {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String myURL = "jdbc:mysql://localhost:3306/is3102db";
            connection = DriverManager.getConnection(myURL, "root", "adminadmin");
            connection.setAutoCommit(false);
        } catch (SQLException exception) {
            exception.printStackTrace();
        }
        return connection;
    }

    public void onRowSelectNavigateBill(SelectEvent event) throws IOException {
//        setSelectedStakeholder((StakeholderEntity) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("stakeholder"));
        selectedStakeholder = selectedBill.getStakeholder();
        System.out.println("selectedStakeholder " + selectedStakeholder.getId());
        System.out.println("selectedBill " + selectedBill.getId());
        String link = "/report/reportBill" + selectedStakeholder.getId() + selectedBill.getId() + ".pdf";
        String serverName = ctx.getExternalContext().getRequestServerName();
        int serverPort = (Integer) ctx.getExternalContext().getSessionMap().get("serverPort");
        String contextPath = ctx.getExternalContext().getRequestContextPath();
        ctx.getExternalContext().redirect("http://" + serverName + ":" + serverPort + contextPath + link);
        FacesContext.getCurrentInstance().getExternalContext().redirect(link);
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public TransactionSessionBean getTransactionSessionBean() {
        return transactionSessionBean;
    }

    public void setTransactionSessionBean(TransactionSessionBean transactionSessionBean) {
        this.transactionSessionBean = transactionSessionBean;
    }

    public StakeholderSessionBeanStateful getStakeholderSessionBean() {
        return stakeholderSessionBean;
    }

    public void setStakeholderSessionBean(StakeholderSessionBeanStateful stakeholderSessionBean) {
        this.stakeholderSessionBean = stakeholderSessionBean;
    }

    public StakeholderEntity getSelectedStakeholder() {
        return selectedStakeholder;
    }

    public void setSelectedStakeholder(StakeholderEntity selectedStakeholder) {
        this.selectedStakeholder = selectedStakeholder;
    }

    public PaymentManagementEntity getSelectedBill() {
        return selectedBill;
    }

    public void setSelectedBill(PaymentManagementEntity selectedBill) {
        this.selectedBill = selectedBill;
    }

    public ReportSessionBean getReportSessionBean() {
        return reportSessionBean;
    }

    public void setReportSessionBean(ReportSessionBean reportSessionBean) {
        this.reportSessionBean = reportSessionBean;
    }
}
